package main

import (
	"fmt"
	goredislib "github.com/go-redis/redis/v8"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
	"sync"
	"time"
)

var redisClient = goredislib.NewClient(&goredislib.Options{
	Addr:     "111.229.176.202:6379",
	Password: "www#1234",
	DB:       2,
})

func main() {
	// 创建 Redsync 实例
	pool := goredis.NewPool(redisClient)
	rs := redsync.New(pool)

	// 创建 WaitGroup 用于等待所有 Goroutine 完成
	var wg sync.WaitGroup

	// 模拟多个 Goroutine 尝试获取锁
	for i := 1; i <= 2; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()

			// 定义锁的名称
			lockName := "my-lock"

			// 创建锁
			mutex := rs.NewMutex(lockName, redsync.WithExpiry(time.Duration(120)*time.Second))

			// 尝试获取锁
			if err := mutex.TryLock(); err != nil {
				// 处理获取锁失败的情况
				fmt.Printf("Goroutine %d: Failed to acquire lock: %v\n", id, err)
				return
			}
			fmt.Printf("Goroutine %d: Lock acquired successfully!\n", id)

			// 模拟一些需要锁保护的代码
			// 这里只是简单地 Sleep 一下，你可以替换成实际的业务逻辑
			time.Sleep(60 * time.Second)

			// 释放锁
			if ok, err := mutex.Unlock(); !ok {
				// 处理释放锁失败的情况
				fmt.Printf("Goroutine %d: Failed to release lock: %v\n", id, err)
				return
			}
			fmt.Printf("Goroutine %d: Lock released successfully!\n", id)
		}(i)
	}

	time.Sleep(10 * time.Second)

	for i := 1; i <= 1; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()

			// 定义锁的名称
			lockName := "my-lock"

			// 创建锁
			mutex := rs.NewMutex(lockName, redsync.WithExpiry(time.Duration(60)*time.Second))

			// 尝试获取锁
			if err := mutex.TryLock(); err != nil {
				// 处理获取锁失败的情况
				fmt.Printf("Goroutine-2 %d: Failed to acquire lock: %v\n", id, err)
				return
			}
			fmt.Printf("Goroutine-2 %d: Lock acquired successfully!\n", id)

			// 模拟一些需要锁保护的代码
			// 这里只是简单地 Sleep 一下，你可以替换成实际的业务逻辑
			time.Sleep(10 * time.Second)

			// 释放锁
			if ok, err := mutex.Unlock(); !ok {
				// 处理释放锁失败的情况
				fmt.Printf("Goroutine-2 %d: Failed to release lock: %v\n", id, err)
				return
			}
			fmt.Printf("Goroutine-2 %d: Lock released successfully!\n", id)
		}(i)
	}

	// 等待所有 Goroutine 完成
	wg.Wait()
}
